<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
*/

/**
 * Description of Extension
 *
 * @author chaporgin_a
 */
class VA_Form_Validator_Extension extends VA_Form_Validator {
    protected $extensions = null;
    public function init($options) {
        parent::init($options);
        $this->extensions = $this->getOption('extensions');
        foreach($this->extensions as $key => $value) $this->extensions[$key] = strtolower($value);
    }
    public function isValid($value) {
        if(empty($value)) return TRUE;
        if(is_array($value)) {
            $valid = TRUE;
            /* @var $v VA_Form_File_TemporaryFile */
            foreach ($value as $v)
                if(!$this->check($v->getPointer())) {
                    $valid = FALSE;
                    break;
                }
        } else $valid = $this->check($value->getFilename());
        if( $valid) return TRUE;
        $this->errorMessages[] = sprintf('Пожалуйста, введите значение с правильным расширением (%s)'
                , join(', ', $this->extensions)
        );
        return FALSE;
    }

    protected function check($extension) {
        if(in_array(strtolower($this->getExt($extension)), $this->extensions))
            return TRUE;
        return FALSE;
    }
    public function getHTMLTagAttributes() {
        return array('accept' => array( join(',', $this->extensions) ));
    }

    protected function getExt($path) {
        $tmp = pathinfo($path);
        return $tmp['extension'];
    }
}

